package com.y.game.emtity;

import java.awt.Color;
import java.awt.Graphics;

import com.y.game.listener.IShapeListener;
import com.y.game.util.Util;

/**
 * 图形类
 */
public class Shape {
	public static final int ROTATE = 1;
	public static final int MOVERIGHT = 2;
	public static final int MOVEDOWN = 3;
	public static final int MOVELEFT = 4;
	private IShapeListener shapeListener;
	private int[][] shapeBody;  // 当前显示的图形
	private int shapeStatus;  // 当前图形的第几种形态 一个图形有多重形态
	private int leftCellNum;  // 距离左侧几个格子  总左侧距离 = leftCellNum * 一个格子宽度
	private int topCellNum;  // 距离顶部几个格子  总顶部距离 = topCellNum * 一个格子高度
	
	// 为图形添加监听器 实现重绘
	public void addShapeListener(IShapeListener shapeListener) {
		this.shapeListener = shapeListener;
		this.autoMoveDown();  // 开始下落
	}
	
	public void moveLeft() {
//System.out.println("Shape moveLeft");
		leftCellNum --;
	}
	
	public void moveRight() {
//System.out.println("Shape moveRight");
		leftCellNum ++;
	}
	
	public void moveDown() {
//System.out.println("Shape moveDown");
		topCellNum ++;
	}
	
	public void rotate() {
//System.out.println("Shape rotate");
		shapeStatus = (shapeStatus + 1) % shapeBody.length;
	}
	
	public void drawMe(Graphics g) {
//System.out.println("Shape drawMe");
		
		Color c = g.getColor();
		g.setColor(Util.GRAPH_COLOR);
		
		for(int x=0; x<4; x++) {
			for(int y=0; y<4; y++) {
//System.out.println(leftCellNum + "--" + topCellNum);
				if(isOneFalg(x, y, false)) {
					g.fill3DRect((leftCellNum + x) * Util.CELL_SIZE, 
							(topCellNum + y) * Util.CELL_SIZE, 
							Util.CELL_SIZE, Util.CELL_SIZE, 
							true);
				}
			}
		}
		
		g.setColor(c);
	}
	
	/**
	 * 计算数组 x 向第 x 个元素 y 向第 y 个元素是否是 1
	 * @param x x 向第几个数
	 * @param y y 向第几个数
	 * @param isRotated 是否旋转了
	 * @return
	 */
	public boolean isOneFalg(int x, int y, boolean isRotated) {
		int temp = shapeStatus;
		if(isRotated) {
			temp = (temp + 1) % shapeBody.length;
		}
		
		return shapeBody[temp][y * 4 + x] == 1;
	}
	
	// 使图形自动下落 这里用一个线程实现
	private class ShapeTickDown implements Runnable {
		
		@Override
		public void run() {
			// 如果注册过图形下落监听器 实现下落后重绘面板
			if(shapeListener != null) {
				while(shapeListener.isShapeMoveable()) {
					moveDown();
					
					shapeListener.moveDown();
					
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	// 启动定时自动下落
	public void autoMoveDown() {
		new Thread(new ShapeTickDown()).start();
	}
	
	// 设置图形
	public void setShapeBody(int[][] shapeBody) {
		this.shapeBody = shapeBody;
	}
	
	// 设置图形当前的形态
	public void setShapeStatus(int shapeStatus) {
		this.shapeStatus = shapeStatus;
	}
	
	public int getLeftCellNum() {
		return this.leftCellNum;
	}
	
	public int getTopCellNum() {
		return this.topCellNum;
	}
}
